import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../api/api_service.dart';
import '../../models/pet.dart';
import '../../utils/app_icons.dart';
import '../../config/app_theme.dart';
import '../../providers/app_state.dart';
import 'pet_detail_screen.dart';
import 'publish_pet_screen.dart';

class AdoptionScreen extends StatefulWidget {
  @override
  _AdoptionScreenState createState() => _AdoptionScreenState();
}

class _AdoptionScreenState extends State<AdoptionScreen> {
  final ApiService _apiService = ApiService();
  List<Pet> _pets = [];
  bool _isLoading = true;
  String _selectedSpecies = '全部';
  
  final List<String> _speciesOptions = ['全部', '猫', '狗', '兔子', '仓鼠', '鸟'];

  @override
  void initState() {
    super.initState();
    _loadPets();
  }

  Future<void> _loadPets() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final pets = await _apiService.getPets(limit: 30);
      
      // 只保留可领养的宠物
      final adoptablePets = pets.where((pet) => pet.isForAdoption).toList();
      
      setState(() {
        _pets = adoptablePets;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      print('Error loading pets: $e');
    }
  }

  List<Pet> get _filteredPets {
    if (_selectedSpecies == '全部') {
      return _pets;
    }
    return _pets.where((pet) => pet.species == _selectedSpecies).toList();
  }

  void _navigateToPetDetail(Pet pet) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PetDetailScreen(pet: pet),
      ),
    );
  }

  void _navigateToPublishPet() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('发布待领养宠物'),
          content: Text('即将添加发布待领养宠物功能，敬请期待！'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('关闭'),
            ),
          ],
        );
      },
    );
    
    // 实际功能可以使用以下代码
    // Navigator.push(
    //   context,
    //   MaterialPageRoute(
    //     builder: (context) => PublishPetScreen(),
    //   ),
    // );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('宠物领养'),
        actions: [
          IconButton(
            icon: Image.asset(AppIcons.search, width: 24, height: 24, color: Colors.white),
            onPressed: () {
              // TODO: 实现宠物搜索功能
            },
          ),
        ],
      ),
      body: Column(
        children: [
          _buildSpeciesFilter(),
          Expanded(
            child: _isLoading
                ? Center(child: CircularProgressIndicator())
                : _filteredPets.isEmpty
                    ? Center(child: Text('没有找到符合条件的宠物'))
                    : RefreshIndicator(
                        onRefresh: _loadPets,
                        child: ListView.builder(
                          padding: EdgeInsets.all(16.0),
                          itemCount: _filteredPets.length,
                          itemBuilder: (context, index) {
                            final pet = _filteredPets[index];
                            return _buildPetCard(pet);
                          },
                        ),
                      ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _navigateToPublishPet,
        backgroundColor: AppTheme.primaryColor,
        child: Image.asset(AppIcons.add, width: 24, height: 24, color: Colors.white),
      ),
    );
  }

  Widget _buildSpeciesFilter() {
    return Container(
      height: 50,
      padding: EdgeInsets.symmetric(vertical: 8.0),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 2,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: EdgeInsets.symmetric(horizontal: 16.0),
        itemCount: _speciesOptions.length,
        itemBuilder: (context, index) {
          final species = _speciesOptions[index];
          final isSelected = species == _selectedSpecies;
          
          return GestureDetector(
            onTap: () {
              setState(() {
                _selectedSpecies = species;
              });
            },
            child: Container(
              margin: EdgeInsets.only(right: 16.0),
              padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0),
              decoration: BoxDecoration(
                color: isSelected ? AppTheme.primaryColor : Colors.transparent,
                borderRadius: BorderRadius.circular(20.0),
                border: Border.all(
                  color: isSelected ? AppTheme.primaryColor : Colors.grey,
                  width: 1.0,
                ),
              ),
              child: Text(
                species,
                style: TextStyle(
                  color: isSelected ? Colors.white : Colors.grey,
                  fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildPetCard(Pet pet) {
    final appState = Provider.of<AppState>(context);
    final bool isFavorite = appState.favoritePets.contains(pet.id);
    
    return GestureDetector(
      onTap: () => _navigateToPetDetail(pet),
      child: Container(
        margin: EdgeInsets.only(bottom: 16.0),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.0),
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 4,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.vertical(top: Radius.circular(10.0)),
                  child: Image.network(
                    pet.images.first,
                    height: 200,
                    width: double.infinity,
                    fit: BoxFit.cover,
                  ),
                ),
                Positioned(
                  top: 8,
                  right: 8,
                  child: InkWell(
                    onTap: () {
                      appState.toggleFavoritePet(pet.id);
                    },
                    child: Container(
                      padding: EdgeInsets.all(8),
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.8),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        isFavorite ? Icons.favorite : Icons.favorite_border,
                        color: isFavorite ? Colors.red : Colors.grey,
                        size: 20,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            Padding(
              padding: EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Expanded(
                        child: Text(
                          pet.name,
                          style: AppTheme.titleStyle,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
                        decoration: BoxDecoration(
                          color: AppTheme.primaryColor.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(4.0),
                        ),
                        child: Text(
                          pet.gender,
                          style: TextStyle(
                            color: AppTheme.primaryColor,
                            fontSize: 12.0,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 8.0),
                  Text(
                    '${pet.species} · ${pet.breed} · ${pet.age}岁',
                    style: AppTheme.bodyStyle,
                  ),
                  SizedBox(height: 8.0),
                  Text(
                    pet.description,
                    style: AppTheme.bodyStyle,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 16.0),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          '发布于 ${_formatDate(pet.createdAt)}',
                          style: AppTheme.captionStyle,
                        ),
                      ),
                      ElevatedButton(
                        onPressed: () => _navigateToPetDetail(pet),
                        style: ElevatedButton.styleFrom(
                          primary: AppTheme.primaryColor,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8.0),
                          ),
                          padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                        ),
                        child: Text('查看详情'),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }
} 